import { defineConfig, type ConfigEnv, loadEnv, type UserConfig } from "vite";
import { root, __APP_INFO__, wrapperEnv } from "./build/utils";
import { createVitePlugins } from "./build/plugins";
import { createProxy } from "./build/proxy";
import { resolve } from "path";

// https://vite.dev/config/
export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  // 这样就可以拿到定义好的环境变量了，也可以使用process.env.xxx这种方式进行访问
  const viteEnv = wrapperEnv(loadEnv(mode, root));
  return {
    base: viteEnv.VITE_PUBLIC_PATH || "/",
    root,
    plugins: createVitePlugins(viteEnv),
    resolve: {
      alias: {
        "@": resolve(__dirname, "./src")
      }
    },
    define: {
      __APP_INFO__: JSON.stringify(__APP_INFO__)
    },
    server: {
      host: "0.0.0.0",
      port: viteEnv.VITE_PORT,
      open: viteEnv.VITE_OPEN,
      cors: true,
      proxy: createProxy(viteEnv.VITE_PROXY),
      // proxy: {
      //   "/admin": {
      //     target: "https://192.168.10.180:8181",
      //     changeOrigin: true,
      //     rewrite: path => path.replace(/^\/admin/, "v1")
      //   }
      // },
      // 预热文件以提前转换和缓存结果，降低启动期间的初始页面加载时长并防止转换瀑布
      warmup: {
        clientFiles: ["./index.html", "./src/{views,components}/*"]
      }
    },
    css: {
      preprocessorOptions: {
        // define global scss variable
        scss: {
          additionalData: `@use "@/styles/index.scss" as *;`
        }
      }
    },
    build: {
      outDir: "dist",
      minify: "esbuild",
      // esbuild 打包更快，但是不能去除 console.log，terser打包慢，但能去除 console.log
      // minify: "terser",
      // terserOptions: {
      // 	compress: {
      // 		drop_console: viteEnv.VITE_DROP_CONSOLE,
      // 		drop_debugger: true
      // 	}
      // },
      sourcemap: false,
      // 禁用 gzip 压缩大小报告，可略微减少打包时间
      reportCompressedSize: false,
      // 规定触发警告的 chunk 大小
      chunkSizeWarningLimit: 2000,
      rollupOptions: {
        output: {
          manualChunks: {
            vendor: ["vue", "vue-router", "pinia", "axios"]
          },
          chunkFileNames: "assets/js/[name]-[hash].js",
          entryFileNames: "assets/js/[name]-[hash].js",
          assetFileNames: "assets/[ext]/[name]-[hash].[ext]"
        }
      }
    }
  };
});
